<template>
  <div class="container">
    <h1>桂林电子科技大学科技园</h1>
    <h2>众创空间退出申请表</h2>

    <el-form
        label-width="150px"
        style="display: flex; flex-wrap: wrap"
        :model="form"
        :rules="rules"
        ref="formRef"
    >
      <el-card>
        <!-- 企业/团队信息 -->
        <el-row :gutter="20" style="width: 100%">
          <el-col :span="12">
            <el-form-item label="企业/团队:" prop="enterpriseTeam">
              <el-input v-model="form.enterpriseTeam" placeholder="请输入企业/团队"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退出时间:" prop="exitTime">
              <el-date-picker
                  v-model="form.exitTime"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择日期"
                  style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 房号及卡座号、经办人、联系方式 -->
        <el-row :gutter="20" style="width: 100%">
          <el-col :span="8">
            <el-form-item label="房号及卡座号:" prop="roomNumber">
              <el-input v-model="form.roomNumber" placeholder="请输入房号及卡座号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经办人:" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入经办人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式:" prop="contactMethod">
              <el-input v-model="form.contactMethod" placeholder="请输入联系方式"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 退出原因 -->
        <el-form-item label="退出原因:" prop="exitReason">
          <el-checkbox-group v-model="form.exitReason">
            <el-checkbox
                v-for="reason in exitReasons"
                :key="reason.value"
                :label="reason.value"
            >
              {{ reason.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-card>
      <!-- 退出后续事宜办理情况 -->
      <el-card>
        <div slot="header" class="header">退出后续事宜办理情况</div>

        <el-row :gutter="20" style="width: 100%">
          <el-col :span="12">
            <el-form-item label="门禁指纹是否清除:" prop="accessControlCleared" label-width="200px">
              <el-radio-group v-model="form.accessControlCleared">
                <el-radio label="true">是</el-radio>
                <el-radio label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司物品是否清出:" prop="companyItemsCleared" label-width="200px">
              <el-radio-group v-model="form.companyItemsCleared">
                <el-radio label="true">是</el-radio>
                <el-radio label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司注册地址是否迁移:" prop="registrationAddressMigrated" label-width="200px">
              <el-radio-group v-model="form.registrationAddressMigrated">
                <el-radio label="true">是</el-radio>
                <el-radio label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司是否注销:" prop="companyDeregistered" label-width="200px">
              <el-radio-group v-model="form.companyDeregistered">
                <el-radio label="true">是</el-radio>
                <el-radio label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card>
        <div slot="header"></div>
        <!-- 已缴纳保证金金额 -->

        <el-form-item label="已缴纳保证金金额(大写):" prop="depositPaid" label-width="180px">
          <el-input v-model="form.depositPaid" placeholder="请输入已缴纳保证金金额">
            <template #append>元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="应退保证金金额(大写):" prop="depositRefundable" label-width="180px">
          <el-input v-model="form.depositRefundable" placeholder="请输入应退保证金金额">
            <template #append>元</template>
          </el-input>
        </el-form-item>
      </el-card>

      <el-card>
        <div slot="header" class="header">退款账户明细</div>
        <el-form-item label="退款账户名:" prop="refundAccountName">
          <el-input v-model="form.refundAccountName" placeholder="请输入退款账户名"></el-input>
        </el-form-item>
        <el-form-item label="退款账号:" prop="refundAccountNumber">
          <el-input v-model="form.refundAccountNumber" placeholder="请输入退款账号"></el-input>
        </el-form-item>
        <!-- 开户银行 -->
        <el-form-item label="开户银行:" prop="refundBank">
          <el-input v-model="form.refundBank" placeholder="请输入开户银行"></el-input>
        </el-form-item>
        <!-- 申请人签名 -->
        <el-form-item label="申请人签名:" prop="applicantSignature">
          <el-input v-model="form.applicantSignature" placeholder="请输入申请人签名"></el-input>
        </el-form-item>

        <!-- 申请人签名日期 -->
        <el-form-item label="申请人签名日期:" prop="applicantSignatureDate">
          <el-date-picker
              v-model="form.applicantSignatureDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-card>
      <!-- 科技园审批 -->
      <el-card>
        <div slot="header" class="header">科技园审批 (以下内容由科技园填写)</div>

        <!-- 退款金额 -->
        <el-form-item label="应退款(大写):">
          <el-input disabled v-model="form.refundAmount" placeholder="请输入退款金额"></el-input>
        </el-form-item>

        <!-- 经手人 -->
        <el-form-item label="经手人:">
          <el-input disabled v-model="form.handler" placeholder="请输入经手人"></el-input>
        </el-form-item>

        <!-- 部门负责人意见 -->
        <el-form-item label="部门负责人意见:">
          <el-input
              disabled
              type="textarea"
              :rows="3"
              v-model="form.departmentHeadOpinion"
              placeholder="请输入部门负责人意见"
          ></el-input>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="saveDraft">保存草稿</el-button>
        </el-form-item>
      </el-card>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {
  editexitApplicationForm,
  editexitCreateSpaceForm,
  exitCreateSpaceForm,
  getexitApplicationForm, getexitexitCreateSpaceForm
} from '@/api/personal-center';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import {onMounted, reactive, ref} from 'vue';
import router from "@/router";
import {useRoute} from "vue-router";
import type { AjaxResult } from '@/types/resultTypes';

const route = useRoute();
const formRef = ref<FormInstance>();
const totalRecord = ref(0);//用来标记用户是不是第一次提交 0，1表示是从我的退出填报中点击编辑过来的

// 表单验证规则
const rules = reactive<FormRules>({
  enterpriseTeam: [
    { required: true, message: '请输入企业/团队名称', trigger: 'blur' }
  ],
  exitTime: [
    { required: true, message: '请选择退出时间', trigger: 'change' }
  ],
  roomNumber: [
    { required: true, message: '请输入房号及卡座号', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入经办人姓名', trigger: 'blur' }
  ],
  contactMethod: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的联系方式', trigger: 'blur' }
  ],
  exitReason: [
    { required: true, message: '请至少选择一个退出原因', trigger: 'change' }
  ],
  accessControlCleared: [
    { required: true, message: '请选择门禁指纹是否清除', trigger: 'change' } 
  ],
  companyItemsCleared: [
    { required: true, message: '请选择公司物品是否清出', trigger: 'change' }
  ],
  registrationAddressMigrated: [
    { required: true, message: '请选择注册地址是否迁出', trigger: 'change' }
  ],
  companyDeregistered: [
    { required: true, message: '请选择公司是否注销', trigger: 'change' }
  ],
  depositPaid: [
    { required: true, message: '请输入已缴纳保证金金额', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' },
  ],
  depositRefundable: [
    { required: true, message: '请输入应退保证金金额', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' },
  ],
  refundAccountName: [
    { required: true, message: '请输入退款账户名', trigger: 'blur' }
  ],
  refundAccountNumber: [
    { required: true, message: '请输入退款账号', trigger: 'blur' },
    { pattern: /^[0-9]{16,19}$/, message: '请输入正确的银行账号', trigger: 'blur' }
  ],
  refundBank: [
    { required: true, message: '请输入开户银行', trigger: 'blur' }
  ],
  applicantSignature: [
    { required: true, message: '请输入申请人签名', trigger: 'blur' }
  ],
  applicantSignatureDate: [
    { required: true, message: '请选择签名日期', trigger: 'change' }
  ]
});
// 退出原因列表选项
const exitReasons = ref([
  { label: '合同期满退出', value: '合同期满退出' },
  { label: '团队申请退出', value: '团队申请退出' },
  { label: '毕业两年退出', value: '毕业两年退出' },
  { label: '清理退出', value: '清理退出' }
]);

// 修改form定义，添加otherReason字段和默认选中"其他原因"
const form = reactive({
  id: 0,
  enterpriseTeam: '',
  roomNumber: '',
  contactPerson: '',
  contactMethod: '',
  exitReason: [] as string[], // 统一使用数组形式
  exitTime: '',
  accessControlCleared: 'false',
  companyItemsCleared: 'false',
  registrationAddressMigrated: 'false',
  companyDeregistered: 'false',
  depositPaid: 0.0,
  depositRefundable: 0.0,
  refundAccountName: '',
  refundAccountNumber: '',
  refundBank: '',
  applicantSignature: '',
  applicantSignatureDate: '',
  refundAmount: 0.0,
  handler: '',
  departmentHeadOpinion: '',
  departmentHeadSignatureDate: '',
  status: 0,
});



// 提交表单
// 提交表单时，将字符串的布尔值转回布尔类型
// 提交表单时，将字符串的布尔值转回布尔类型
const submitForm = async () => {
  if (!formRef.value) {
    ElMessage.error('表单未初始化');
    return;
  }

  try {
    await formRef.value.validate();

    // 准备提交数据
    const formData: any = {
      ...form,
      exitReason: form.exitReason.join(','),
      status: 1,
      // 将字符串的布尔值转回布尔类型
      accessControlCleared: form.accessControlCleared === 'true',
      companyItemsCleared: form.companyItemsCleared === 'true',
      registrationAddressMigrated: form.registrationAddressMigrated === 'true',
      companyDeregistered: form.companyDeregistered === 'true'
    };

    // 提交逻辑
    if (totalRecord.value === 0) {
      await exitCreateSpaceForm(formData);
      router.push('/personal-center/graduation-or-exit/my-exit');
      ElMessage.success('提交成功');

    } else {
      await editexitCreateSpaceForm(formData);
      router.push('/personal-center/graduation-or-exit/my-exit');
      ElMessage.success('修改成功');
    }
    
    
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error('请完善表单信息');
  }
};



// 保存草稿
// 保存草稿时，处理otherReason字段
const saveDraft = async () => {

    if (!formRef.value) {
      ElMessage.error('表单未初始化');
      return;
    }

    try {
      await formRef.value.validate();

      // 准备提交数据
      const formData: any = {
        ...form,
        exitReason: form.exitReason.join(','),
        status: 0,
        // 将字符串的布尔值转回布尔类型
        accessControlCleared: form.accessControlCleared === 'true',
        companyItemsCleared: form.companyItemsCleared === 'true',
        registrationAddressMigrated: form.registrationAddressMigrated === 'true',
        companyDeregistered: form.companyDeregistered === 'true'
      };

      // 提交逻辑
      if (totalRecord.value === 0) {
        await exitCreateSpaceForm(formData);
        router.push('/personal-center/graduation-or-exit/my-exit');
        ElMessage.success('保存成功');
      } else {
        await editexitCreateSpaceForm(formData) ;
        router.push('/personal-center/graduation-or-exit/my-exit');
        ElMessage.success('修改成功');
      }
      
    } catch (error) {
      console.error('表单验证失败:', error);
      ElMessage.error('请完善表单信息');
    }
  };

// 获取用户未提交的报表数据
// 修改getUserDraft方法，处理otherReason字段
// 修改getUserDraft方法，将布尔值转换为字符串
const getUserDraft = async (id: number) => {
  try {
    const res = await getexitexitCreateSpaceForm(id) as unknown as AjaxResult<any>;
    if (res.code === 200) {
      Object.keys(form).forEach(key => {
        if (key in res.data) {
          // 特殊处理布尔值字段
          if (['accessControlCleared', 'companyItemsCleared', 'registrationAddressMigrated', 'companyDeregistered'].includes(key)) {
            form[key] = res.data[key] ? 'true' : 'false'; // 将布尔值转换为字符串
          }
          // 为布尔字段设置默认值
          if (['accessControlCleared', 'companyItemsCleared', 'registrationAddressMigrated', 'companyDeregistered'].includes(key)) {
            form[key] = String(res.data[key] ?? false); // 如果后端返回null或undefined，使用默认值false
          }
          // 处理exitReason字段
          else if (key === 'exitReason') {
            form.exitReason = res.data.exitReason ? res.data.exitReason.split(',') : [];
          }
          // 其他字段直接赋值
          else {
            form[key] = res.data[key];
          }
        }
      });
    }
  } catch (error) {
    console.error('获取报表数据失败:', error);
    ElMessage.error('获取报表数据失败');
  }
};

onMounted(() => {
  const id = route.query.id;
  if (id) {
    totalRecord.value = 1;
    getUserDraft(Number(id));
  }
});
</script>

<style scoped lang="scss">
.header {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
}
.el-card {
  width: 100%;
  margin: 10px auto;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}
</style>